﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WXYW.BLL;
using WXYW.DAL;
using WXYW.Model;
using System.Collections;

namespace WXYW
{
    public partial class RWGLSearch : System.Web.UI.Page
    {
        public int RecordsNumber { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitialDropDown();
                BindTask();
                //BindOverdueList();
            }
        }

        private void BindOverdueList()
        {
            TaskService service = new TaskService();
            List<Task> tasks = service.GetAllFinishedTask().ToList();

            List<Task> overduetasks = tasks.Where(t => t.CompleteDate > t.ShouldCompleteDate).ToList();
            List<string> persons = new List<string>();
            foreach (Task task in overduetasks)
            {
                if (!task.UserReference.IsLoaded)
                {
                    task.UserReference.Load();
                }
                persons.Add(task.User.ContactPerson);
            }
            persons = persons.Distinct().ToList();
            List<TaskModel> models = new List<TaskModel>();
            foreach (string person in persons)
            {
                TaskModel model = new TaskModel();
                int totalTasks = tasks.Where(t => t.User.ContactPerson == person).Count();
                model.Person = person;
                model.Times = overduetasks.Where(t => t.User.ContactPerson == person).Count();
                model.Percents = model.Times / Convert.ToDouble(totalTasks);
                model.TotalTasks = totalTasks;
                models.Add(model);
            }

            models = models.OrderBy(m => m.Times).ToList();
            overDuePerpleGridView.DataSource = models;
            overDuePerpleGridView.DataBind();
        }

        private void BindTask()
        {
            TaskService service = new TaskService();
            List<Task> tasks = service.GetTasksByYearMonthService(Convert.ToInt32(yearDropDownList.SelectedValue), Convert.ToInt32(monthDropDownList.SelectedValue),
                Convert.ToInt32(tyearDropDownList.SelectedValue), Convert.ToInt32(tmonthDropDownList.SelectedValue),
                Convert.ToInt32(servicestationDropDownList.SelectedValue), keywordTxtBox.Text.Trim()).ToList();
            taskGridView.DataSource = tasks;
            taskGridView.DataBind();

            List<Task> overduetasks = tasks.Where(t => (t.CompleteDate.HasValue && t.CompleteDate > t.ShouldCompleteDate) ||
                (!t.CompleteDate.HasValue && t.ShouldCompleteDate.Value < DateTime.Now)).ToList();
            List<string> persons = new List<string>();
            foreach (Task task in overduetasks)
            {
                if (!task.UserReference.IsLoaded)
                {
                    task.UserReference.Load();
                }
                persons.Add(task.User.ContactPerson);
            }
            persons = persons.Distinct().ToList();
            List<TaskModel> models = new List<TaskModel>();
            foreach (string person in persons)
            {
                TaskModel model = new TaskModel();
                int totalTasks = tasks.Where(t => t.User.ContactPerson == person).Count();
                model.Person = person;
                model.Times = overduetasks.Where(t => t.User.ContactPerson == person).Count();
                model.Percents = model.Times * 100 / Convert.ToDouble(totalTasks);
                model.TotalTasks = totalTasks;
                models.Add(model);
            }

            models = models.OrderBy(m => m.Times).ToList();
            overDuePerpleGridView.DataSource = models;
            overDuePerpleGridView.DataBind();

            RecordsNumber = tasks.Count;
        }

        private void InitialDropDown()
        {
            for (int i = 2010; i <= DateTime.Now.Year; i++)
            {
                yearDropDownList.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }
            yearDropDownList.SelectedIndex = yearDropDownList.Items.Count - 1;

            for (int i = 2010; i <= DateTime.Now.Year; i++)
            {
                tyearDropDownList.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }
            tyearDropDownList.SelectedIndex = tyearDropDownList.Items.Count - 1;

            for (int i = 1; i <= 12; i++)
            {
                monthDropDownList.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }
            monthDropDownList.SelectedIndex = DateTime.Now.Month == 1 ? 0 : DateTime.Now.Month - 2;

            for (int i = 1; i <= 12; i++)
            {
                tmonthDropDownList.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }
            tmonthDropDownList.SelectedIndex = DateTime.Now.Month - 1;

            ServiceStationService service = new ServiceStationService();
            List<ServiceStation> stations = new List<ServiceStation>();
            stations.Add(new ServiceStation { ID = 0, Name = "所有平台" });
            stations.AddRange(service.GetALLServiceStations().ToList());
            servicestationDropDownList.DataSource = stations;
            servicestationDropDownList.DataTextField = "Name";
            servicestationDropDownList.DataValueField = "ID";
            servicestationDropDownList.DataBind();
        }

        protected void searchButton_Click(object sender, EventArgs e)
        {
            BindTask();
        }

        protected void taskGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            if (e.NewPageIndex >= 0 && e.NewPageIndex < taskGridView.PageCount)
            {
                taskGridView.PageIndex = e.NewPageIndex;
            }
            
            BindTask();
        }

        protected void taskGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem != null)
            {
                Task task = (Task)e.Row.DataItem;
                if (task.CompleteDate.HasValue && (task.CompleteDate > task.ShouldCompleteDate))
                {
                    Label overdue = (Label)e.Row.FindControl("overdueLabel");

                    overdue.Text = "!" + DateTimeService.CalculateDateTimeSpan(task.ShouldCompleteDate.Value, task.CompleteDate.Value.Date);
                }
                if (!task.CompleteDate.HasValue &&
                    DateTime.Now > task.ShouldCompleteDate)
                {
                    Label overdue = (Label)e.Row.FindControl("overdueLabel");
                    overdue.Text = "!" + DateTimeService.CalculateDateTimeSpan(task.ShouldCompleteDate.Value, DateTime.Now);
                }
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FFFF99'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
                ((Label)e.Row.FindControl("IDLbl")).Text = (e.Row.RowIndex + 1).ToString();
            }

            if (e.Row.RowType == DataControlRowType.Pager)
            {
                DropDownList pageDDL = e.Row.FindControl("pageDDL") as DropDownList;
                for (int index = 1; index <= taskGridView.PageCount; index++)
                {
                    pageDDL.Items.Add(index.ToString());
                }
                pageDDL.SelectedValue = (taskGridView.PageIndex + 1).ToString();
            }
        }

        protected void overDuePerpleGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem != null)
            {
                TaskModel model = e.Row.DataItem as TaskModel;
                Image chart = e.Row.FindControl("Image1") as Image;
                double percent = Math.Round(model.Percents, 2);
                chart.ImageUrl = GetChartURL(percent);

                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FFFF99'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
                ((Label)e.Row.FindControl("IDLbl")).Text = (e.Row.RowIndex + 1).ToString();
            }
        }

        string GetChartURL(double percent)
        {
            string url = "http://chart.apis.google.com/chart?cht=bhs&chs=150x20&chco=CC0000,FFFF00&chd=t:{0}|100";

            return string.Format(url, percent);
        }

        protected void overDuePerpleGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            if (e.NewPageIndex >= 0 && e.NewPageIndex < overDuePerpleGridView.PageCount)
            {
                overDuePerpleGridView.PageIndex = e.NewPageIndex;
            }
            
            BindOverdueList();
        }

        protected void modifyLinkButton_click(object sender, EventArgs e)
        {
            Response.Redirect(string.Format("RWGLDetailReadOnly.aspx?TID={0}", ((LinkButton)sender).CommandArgument));
        }

        protected IEnumerable GridView_MustAddARow(IEnumerable data)
        {
            List<Task> dds = new List<Task>();
            dds.Add(new Task());
            return dds;
        }

        protected void pageDDL_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList pageDDL = sender as DropDownList;
            taskGridView.PageIndex = Convert.ToInt32(pageDDL.SelectedIndex);
            BindTask();
        }

        protected void taskGridView_DataBound(object sender, EventArgs e)
        {
            if (taskGridView.BottomPagerRow != null)
            {
                taskGridView.BottomPagerRow.Visible = true;
            }
        }

        protected IEnumerable OverdueGridView_MustAddARow(IEnumerable data)
        {
            List<TaskModel> dds = new List<TaskModel>();
            dds.Add(new TaskModel());
            return dds;
        }
    }
}
